"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
from collections import deque
class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
        if not root:
            return root
        a=deque([(root,0)])
        while a:
            cur, n= a.popleft()
            if cur.left:
                a.append((cur.left,n+1))
                a.append((cur.right,n+1))
            if a and a[0][1]==n:
                cur.next=a[0][0]
        return root

        

        